package com.room2.adapter;

import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.room2.R;
import com.room2.model.Score;
import com.room2.ui.ScoreViewModel;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyScoreAdapter extends RecyclerView.Adapter<MyScoreAdapter.ViewHolder> {

    private List<Score> list = new ArrayList<>();
    ScoreViewModel viewModel;

    public MyScoreAdapter(ScoreViewModel viewModel) {
        this.viewModel = viewModel;
    }

    public void setList(List<Score> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_score, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final Score score = list.get(position);
        holder.tv_id.setText("" + score.getId());
        holder.tv_name.setText(score.getSubject());
        holder.tv_score.setText("" + score.getScore());
        holder.sw.setOnCheckedChangeListener(null);
        if (score.isShowScore()) {
            holder.sw.setChecked(true);
            holder.tv_score.setVisibility(View.VISIBLE);
        } else {
            holder.sw.setChecked(false);
            holder.tv_score.setVisibility(View.GONE);
        }

        holder.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    score.setShowScore(true);
                    holder.tv_score.setVisibility(View.VISIBLE);
                } else {
                    score.setShowScore(false);
                    holder.tv_score.setVisibility(View.GONE);
                }
                viewModel.update(score);
            }
        });


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv_id, tv_name, tv_score;
        Switch sw;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_id = itemView.findViewById(R.id.tv_id);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_score = itemView.findViewById(R.id.tv_score);
            sw = itemView.findViewById(R.id.sw);
        }
    }
}
